<template>
	<view>
		<view class="form">
			<uni-forms ref="form" :modelValue="formData" :rules="rules">
				<uni-forms-item label="姓名" name="name">
					<uni-easyinput type="text" v-model="formData.name" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="邮箱" name="email">
					<uni-easyinput type="text" v-model="formData.email" placeholder="请输入邮箱" />
				</uni-forms-item>
				<uni-forms-item label="权限">
					<picker @change="bindPickerChange" :value="index" :range="array" class="picker">
						<view class="uni-input">{{array[index]}}</view>
					</picker>
				</uni-forms-item>
			</uni-forms>
			<button @click="submit">Submit</button>
		</view>
	</view>
</template>

<script>
	import {
		getInviteCode
	} from '../../api/getInviteCode.js'
	import { getInviteCodeAndSend } from '../../api/getInviteCode.js'
	export default {
		data() {
			return {
				// 表单数据
				formData: {
					name: '',
					email: ''
				},
				rules: {
					name: {
						rules: [{
                            required: true,
                            errorMessage: '请输入姓名',
                        },
						{
							minLength: 2,
							maxLength: 5,
							errorMessage: '姓名长度在 {minLength} 到 {maxLength} 个字符',
						}]
					},
					// 对email字段进行必填验证
					email: {
						rules: [{
							required: true,
							errorMessage: '请输入邮箱',
						}, {
							format: 'email',
							errorMessage: '请输入正确的邮箱地址',
						}]
					}
				},
				array: ['请选择', '超级管理员', '教师用户', '学生用户'],
				index: 0,
				inviteCode: ''
			}
		},
		onLoad() {
			this.getInviteCode()
		},
		methods: {
			submit() {
				this.$refs.form.validate().then(async res => {
					if(this.index == 0){
						return uni.showToast({
							title:'请选择分配权限',
							icon:'error'
						})
					}
					res.role = this.index
					const response = await getInviteCodeAndSend(res)
					if(response.statusCode === 200){
						uni.showModal({
							title: '已成功发送',
							content: '发送的邀请码为'+ this.inviteCode,
							showCancel:false
						})
					}
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			bindPickerChange: function(e) {
				this.index = e.target.value
			},
			async getInviteCode(){
				const res = await getInviteCode()
				if(res.statusCode === 200){
					this.inviteCode = res.data.data
				}
			}
		}
	}
</script>

<style lang="less">
	.form {
		padding-left: 30rpx;
		margin-top: 30rpx;
		.picker {
			line-height: 85rpx;
			border-bottom: 1px solid #ccc;
		}
	}
</style>
